﻿using AppService.IService.Basic_information;
using AppService.IService.Exception;
using AppService.IService.Financial_Management;
using AppService.IService.ICargo_mentSrevice;
using AppService.IService.Sys_statistics;
using AppService.IService.System_Carrier_ment;
using AppService.IService.System_dictionary;
using AppService.IService.System_numbering;
using AppService.IService.System_operation;
using AppService.IService.System_order;
using AppService.IService.System_setting;
using AppService.IService.Vehicle_tracks;
using AppService.Service.Basic_information;
using AppService.Service.Cargo_mentSrevice;
using AppService.Service.ChildrenService;
using AppService.Service.Exception_log;
using AppService.Service.Financial_Management;
using AppService.Service.Sys_statistics;
using AppService.Service.System_Carrier_ment;
using AppService.Service.System_dictionary;
using AppService.Service.System_numbering;
using AppService.Service.System_operation;
using AppService.Service.System_order;
using AppService.Service.System_setting;
using AppService.Service.Vehicle_tracks;
using Autofac.Core;
using Domain.IRepository.Basic_information;
using Domain.IRepository.Exception;
using Domain.IRepository.Financial_Management;
using Domain.IRepository.ICargo_mentRepository;
using Domain.IRepository.Sys_statistics;
using Domain.IRepository.System_Carrier_ment;
using Domain.IRepository.System_dictionary;
using Domain.IRepository.System_numbering;
using Domain.IRepository.System_operation;
using Domain.IRepository.System_Order;
using Domain.IRepository.System_setting;
using Domain.IRepository.Vehicle_tracks;
using EFCore;
using EFCore.Repository.Basic_information;
using EFCore.Repository.Cargo_mentRepository;
using EFCore.Repository.Exception;
using EFCore.Repository.Financial_Management;
using EFCore.Repository.Sys_statistics;
using EFCore.Repository.System_Carrier_ment;
using EFCore.Repository.System_dictionary;
using EFCore.Repository.System_numbering;
using EFCore.Repository.System_operation;
using EFCore.Repository.System_order;
using EFCore.Repository.System_setting;
using EFCore.Repository.Vehicle_tracks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.FileProviders;
using Microsoft.OpenApi.Models;
using TMS_BackEnd.Filters;
using Volo.Abp;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Autofac;
using Volo.Abp.Modularity;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace WebAPI
{
    [DependsOn(typeof(AbpAspNetCoreMvcModule),
        typeof(AbpAutofacModule))]
    public class WebAPIModule : AbpModule
    {

        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            context.Services.AddControllers();
            context.Services.AddScoped<IEmployeeRepository, EmployeeRepository>();
            context.Services.AddScoped<IEmployeeService, EmployeeService>();
            context.Services.AddScoped<ITreeService, TreeService>();
            context.Services.AddScoped<ITreeRepository, TreeRepository>();
            context.Services.AddScoped<IOrderRepository, OrderRepository>();
            context.Services.AddScoped<IorderService, OrderService>();
            context.Services.AddScoped<IBHRepository, BHRepository>();
            context.Services.AddScoped<IBHService, BHService>();
            context.Services.AddScoped<IChildrenRepoitory, ChildrenRepoitory>();
            context.Services.AddScoped<IChildrenService, ChildrenSevice>();
            context.Services.AddScoped<ISys_Dict_dataService, Sys_Dict_dataService>();
            context.Services.AddScoped<ISys_dict_dataRepository, Sys_Dict_dataRepoitory>();
            context.Services.AddScoped<IDepartService, DepartService>();
            context.Services.AddScoped<IDepartRepository, DepartRepository>();
            context.Services.AddScoped<ICompanyRepository, CompanyRepository>();
            context.Services.AddScoped<ICompanyService, CompanyService>();
            context.Services.AddScoped<IBill_olRepository, Bill_olRepository>();
            context.Services.AddScoped<IBill_olService, Bill_olService>();
            context.Services.AddScoped<IDriversRepository, DriversRepository>();
            context.Services.AddScoped<IDriversService, DriversService>();
            context.Services.AddScoped<ICarrier_mentRepository, Carrier_mentRepository>();
            context.Services.AddScoped<ICarrier_mentService, Carrier_mentService>();
            context.Services.AddScoped<IVehiclesRepository, VehiclesRepository>();
            context.Services.AddScoped<IVehiclesService, VehiclesService>();
            context.Services.AddScoped<ICargo_mentRepository,Cargo_mentRepository>();
            context.Services.AddScoped<ICargo_mentSrevice, Cargo_mentSrevice>();
            context.Services.AddScoped<ICt_Repository, Ct_Repository>();
            context.Services.AddScoped<ICt_Service, Ct_Service>();
            context.Services.AddScoped<IAddress_mentRepository, Address_mentRepository>();
            context.Services.AddScoped<IAddress_mentService, Address_mentService>();
            context.Services.AddScoped<IArrival_meterRepository, Arrival_meterRepository>();
            context.Services.AddScoped<IArrival_meterService, Arrival_meterService>();
            context.Services.AddScoped<ISignature_receiptRepository, Signature_receiptRepository>();
            context.Services.AddScoped<ISignature_receiptService, Signature_receiptService>();
            context.Services.AddScoped<IRoleService, RoleService>();
            context.Services.AddScoped<IRoleRepository, RoleRepository>();
            context.Services.AddScoped<IEmployeeService, EmployeeService>();
            context.Services.AddScoped<IEmployeeRepository, EmployeeRepository>();
            context.Services.AddScoped<IWb_meterService, Wb_meterService>();
            context.Services.AddScoped<IWb_meterRepository, Wb_meterRepository>();
            context.Services.AddScoped<ITrackRepository, TracksRepository>();
            context.Services.AddScoped<ITracksService, TracksService>();
            context.Services.AddScoped<IReceipt_meterRepository, Receipt_meterRepository>();
            context.Services.AddScoped<IReceipt_meterService, Receipt_meterService>();
            context.Services.AddScoped<IDriver_statisticsRepository, Driver_statisticsRepository>();
            context.Services.AddScoped<IDriver_statisticsService, Driver_statisticsService>();
            context.Services.AddScoped<IAnomaly_statisticsRepository, Anomaly_statisticsRepository>();
            context.Services.AddScoped<IAnomaly_statisticsService, Anomaly_statisticsService>();
            context.Services.AddScoped<IExceRepository, ExceRepository>();
            context.Services.AddScoped<IExceService, ExceService>();
            context.Services.AddScoped<IReceivable_meterRepository, Receivable_meterRepository>();
            context.Services.AddScoped<IReceivable_meterService, Receivable_meterService>();
            context.Services.AddScoped<IPayable_meterRepository,Payable_meterRepository>();
            context.Services.AddScoped<IPayable_meterService, Payable_meterService>();
            context.Services.AddScoped<IOrder_statisticsRepository, Order_statisticsRepository>();
            context.Services.AddScoped<IOrder_statisticsService, Order_statisticsService>();

            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            context.Services.AddEndpointsApiExplorer();
            context.Services.AddSwaggerGen();
            

            //新增注释
            context.Services.AddSwaggerGen(e =>
            {
                #region 为Swagger JSON and UI设置xml文档注释路径 
                string basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录（绝对，不受工作目录影响，建议采用此方法获取路径）
                string xmlPath = Path.Combine(basePath, "WebAPI.xml");
                e.IncludeXmlComments(xmlPath);
                #endregion
            });

            context.Services.AddSwaggerGen(c =>
            {
                #region Swagger中调试带JWT的请求
                var scheme = new OpenApiSecurityScheme()
                {
                    Description = "Authorization header. \r\nExample: 'Bearer 12345abcdef'",
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = "Authorization"
                    },
                    Scheme = "oauth2",
                    Name = "Authorization",
                    In = ParameterLocation.Header,
                    Type = SecuritySchemeType.ApiKey,
                };
                c.AddSecurityDefinition("Authorization", scheme);
                var requirement = new OpenApiSecurityRequirement();
                requirement[scheme] = new List<string>();
                c.AddSecurityRequirement(requirement);
                #endregion
            });

            context.Services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            });

            context.Services.AddScoped<HelperFilter>();

            //跨域
            string[] urls = new[] { "http://localhost:8080" };
            context.Services.AddCors(options =>
                options.AddDefaultPolicy(builder => builder.WithOrigins(urls)
                .AllowAnyMethod().AllowAnyHeader().AllowCredentials()));    

            //读取sqlserver
            context.Services.AddDbContext<MyDbContext>(options =>
            {
                // 先获取配置对象
                var config = context.Services.GetConfiguration();
                var connectionString = config.GetConnectionString("SqlConnection");
                options.UseSqlServer(connectionString);
                //  options.UseSqlServer("SqlConnection");
            });
        }

        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var app = context.GetApplicationBuilder();
            var env = context.GetEnvironment();
            // Configure the HTTP request pipeline.
            if (env.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            app.UseCors();

            //添加静态文件中间件
            app. UseStaticFiles();
            /*app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(
                  Path.Combine(Directory.GetCurrentDirectory(), @"images")),
                RequestPath = new PathString("/StaticFiles")
            });*/

            //鉴权
            app.UseAuthentication();

            //授权
            app.UseAuthorization();

            //app.UseAuthorization();
        }

    }
}
